package com.winz.cultureapp.fragment;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.mine.xrecyclerview.XRecyclerView;
import com.mine.xrecyclerview.rcvadapter.OnItemClickListener;
import com.winz.cultureapp.R;
import com.winz.cultureapp.activity.ActvitiyDesActivity;
import com.winz.cultureapp.activity.ArtAppreciateActivity;
import com.winz.cultureapp.activity.CommunityActivity;
import com.winz.cultureapp.activity.ExhibitionActivity;
import com.winz.cultureapp.activity.IntangibleActivity;
import com.winz.cultureapp.activity.MoreArtActivity;
import com.winz.cultureapp.activity.NewsActivity;
import com.winz.cultureapp.activity.VolunteerActivity;
import com.winz.cultureapp.adapter.xrcv.HomeDataAdapter;
import com.winz.cultureapp.base.BaseFragment;
import com.winz.cultureapp.constants.Constants;
import com.winz.cultureapp.entity.ActivityListBean;
import com.winz.cultureapp.entity.EventBusBean;
import com.winz.cultureapp.entity.HomeBannertBean;
import com.winz.cultureapp.http.OnResponeListener;
import com.winz.cultureapp.http.request.RequestFactory;
import com.winz.cultureapp.http.util.HttpUitls;
import com.winz.cultureapp.imgloader.GlideImageLoader;
import com.winz.cultureapp.utils.JsonUtil;
import com.winz.cultureapp.utils.Logger;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener, XRecyclerView.LoadingListener, OnItemClickListener {
    @BindView(R.id.fl_back)
    public FrameLayout mFl_back;
    @BindView(R.id.tv_top_title)
    public TextView mTv_top_title;
    @BindView(R.id.iv_right)
    public ImageView mIv_right;

    @BindView(R.id.xrcv_home)
    public XRecyclerView mXrcv_home;

    private boolean isRefresh = true;
    private int limit = 10;
    private int page = 1;
    private int totalPage = 0;

    private int unitId; // 单位ID
    private int areaId; // 区域ID
    private int categoryId; // 分类ID
    private int sort; // 0默认1人气最高2最新发布

    private List<ActivityListBean.DataBean.ListBean> mDatas;
    private HomeDataAdapter mAdapter;

    Banner mBanner;
    private List<HomeBannertBean.DataBean.ListBean> mDatas_banner;
    private List<String> images = new ArrayList<>();
    private List<String> titles = new ArrayList<>();

    public static HomeFragment getInstance() {
        HomeFragment fragment = new HomeFragment();

        return fragment;
    }

    @Override
    protected int contentView() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initViews(View view) {
        mDatas = new ArrayList<>();
        mDatas_banner = new ArrayList<>();
        images = new ArrayList<>();
        titles = new ArrayList<>();

        mTv_top_title.setText(getString(R.string.home_top_title));
//        mIv_right.setImageResource(R.drawable.icon_search);
//        mIv_right.setVisibility(View.VISIBLE);
        mFl_back.setVisibility(View.GONE);


        // XrecyclerView
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mXrcv_home.setLayoutManager(manager);
        mXrcv_home.setPullRefreshEnabled(true);
        mXrcv_home.setLoadingMoreEnabled(false);

        mXrcv_home.setFocusable(false);
        mXrcv_home.setFocusableInTouchMode(false);

        mAdapter = new HomeDataAdapter(mContext, mDatas, R.layout.empty_view, R.layout.item_home_list);
        // 添加头部
        View header = LayoutInflater.from(mContext).inflate(R.layout.view_header_home, null);
        mXrcv_home.addHeaderView(header);
        // 初始化头部信息
        initHeaerView(header);
    }

    private void initHeaerView(View header) {
        mBanner = header.findViewById(R.id.banner);
        header.findViewById(R.id.ll_header_item1).setOnClickListener(this);
        header.findViewById(R.id.ll_header_item2).setOnClickListener(this);
        header.findViewById(R.id.ll_header_item3).setOnClickListener(this);
        header.findViewById(R.id.ll_header_item4).setOnClickListener(this);
        header.findViewById(R.id.ll_header_item5).setOnClickListener(this);
        header.findViewById(R.id.ll_header_item6).setOnClickListener(this);
        header.findViewById(R.id.ll_header_item7).setOnClickListener(this);
        header.findViewById(R.id.ll_header_item8).setOnClickListener(this);
        header.findViewById(R.id.ll_header_item9).setOnClickListener(this);
        header.findViewById(R.id.ll_header_item10).setOnClickListener(this);
    }

    @Override
    protected void initEvents() {


        mXrcv_home.setAdapter(mAdapter);
        mXrcv_home.setLoadingListener(this);
        mAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void loadDatas() {
        getList();
        getBanner();
    }

    /**
     * 获取数据列表
     */
    private void getList() {
        showProgressDialog();

        HttpUitls.onGet("activity", RequestFactory.getInstance().activity(page+"",limit+"",unitId + "",areaId+ "",categoryId+ "",sort+ ""), new OnResponeListener<ActivityListBean>() {
            @Override
            public void onSuccess(ActivityListBean activityListBean) {
                Logger.d("activity==>>", JsonUtil.getJsonFromObj(activityListBean));
                if (activityListBean.code == 0) {
                            totalPage = activityListBean.totalPage;
                    if (activityListBean.data.list != null && activityListBean.data.list.size() > 0) {
                        mXrcv_home.setLoadingMoreEnabled(true);
                        if (isRefresh) {
                            mDatas.clear();
                            mDatas = activityListBean.data.list;
                        } else {
                            mDatas.addAll(activityListBean.data.list);
                        }
                    } else {
                        mDatas.clear();
                        ActivityListBean.DataBean.ListBean empty = new ActivityListBean.DataBean.ListBean();
                        empty.layout_type = -1;
                        mDatas.add(empty);
                        mXrcv_home.setLoadingMoreEnabled(false);
                    }
                    mAdapter.setDatas(mDatas);
                } else {
                    showMsg(activityListBean.msg);
                }
                if (isRefresh) {
                    mXrcv_home.refreshComplete();
                } else {
                    mXrcv_home.loadMoreComplete();
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                dismissProgressDialog();
                Logger.d("activity==>>", error);
                if (isRefresh) {
                    mXrcv_home.refreshComplete();
                } else {
                    mXrcv_home.loadMoreComplete();
                }
            }
        });
    }

    /**
     * 获取轮播列表
     */
    private void getBanner() {
        HttpUitls.onGet("homeBanner", new OnResponeListener<HomeBannertBean>() {
            @Override
            public void onSuccess(HomeBannertBean homeBannertBean) {
                Logger.d("homeBanner==>>", JsonUtil.getJsonFromObj(homeBannertBean));
                if (homeBannertBean.code == 0) {
                    mDatas_banner = homeBannertBean.data.list;
                    images.clear();
                    titles.clear();
                    for (HomeBannertBean.DataBean.ListBean listBean : mDatas_banner) {
                        images.add(listBean.carouselUrl);
                        titles.add(listBean.title);
                    }

                    //设置图片加载器
                    mBanner.setImageLoader(new GlideImageLoader());
                    //设置图片集合
                    mBanner.setImages(images);
                    mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
                    /* LEFT  CENTER  RIGHT 指示器居左,中,右 */
                    mBanner.setIndicatorGravity(BannerConfig.LEFT);
                    mBanner.setBannerTitles(titles);
                    mBanner.setDelayTime(3000);
//                    mBanner.setOnBannerListener(new OnBannerListener() {
//                        @Override
//                        public void OnBannerClick(int position) {
//                            if (mDatas_banner.get(position).carouselUrl.startsWith("http")) {
//                                // 调用系统默认浏览器处理url
//                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mDatas_banner.get(position).carouselUrl)));
//                            } else {
////                        showMsg("该链接不是http");
//                            }
//                        }
//                    });
                    //banner设置方法全部调用完毕时最后调用
                    mBanner.start();
                }
            }

            @Override
            public void onFailed(String error) {

            }
        });
    }

    @OnClick({R.id.rl_right})
    public void knife(View view) {
        switch (view.getId()) {
            case R.id.rl_right:
                showMsg("开发中");
                break;
        }
    }

    /**
     * 头部的点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_header_item1: // 文化团体
                startActivity(CommunityActivity.class, false);
                break;
            case R.id.ll_header_item2: // 新闻资讯
                startActivity(NewsActivity.class, false);
                break;
            case R.id.ll_header_item3: // 志愿服务
                startActivity(VolunteerActivity.class, false);
                break;
            case R.id.ll_header_item4: // 文化场馆
                startActivity(ExhibitionActivity.class, false);
                break;
            case R.id.ll_header_item5: // 文化非遗
                startActivity(IntangibleActivity.class, false);
                break;

            case R.id.ll_header_item6: // 艺术鉴赏
                startActivity(ArtAppreciateActivity.class, false);
                break;
            case R.id.ll_header_item7: // 文物鉴赏
                startActivity(MoreArtActivity.class, false);
                break;
            case R.id.ll_header_item8: // 文体活动
                EventBus.getDefault().post(new EventBusBean(2,20,"文体活动"));
                break;
            case R.id.ll_header_item9: // 场馆预定
                EventBus.getDefault().post(new EventBusBean(2,21,"场馆预定"));
                break;
            case R.id.ll_header_item10: // 个人中心
                EventBus.getDefault().post(new EventBusBean(2,22,"个人中心"));
                break;
        }
    }


    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        isRefresh = true;
        page = 1;
        loadDatas();
    }

    /**
     * 加载
     */
    @Override
    public void onLoadMore() {
        isRefresh = false;
        if (page >= totalPage) {
            mXrcv_home.setNoMore(true, true, "没有更多数据了");
        } else {
            page++;
            loadDatas();
        }
    }

    /**
     * item点击事件
     *
     * @param parent
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(ViewGroup parent, View view, int position) {
        position = position-1;

        Bundle bundle = new Bundle();
        bundle.putSerializable(Constants.KEY.ACTIVITY.ITEM_ID, mDatas.get(position).activityId);
        bundle.putString(Constants.KEY.ACTIVITY.ITEM_DES_HREF,Constants.URL.IP + "/activity/detail/" + mDatas.get(position).activityId);

        startActivity(ActvitiyDesActivity.class,false,bundle);
    }

    @Override
    public boolean onItemLongClick(ViewGroup parent, View view, int position) {
        return false;
    }
}
